# -*- coding: utf-8 -*-

from openerp import models, fields, api


class bc_planbill_detail(models.Model):
    _name = 'bc.planbill.detail'

    planbill_id = fields.Many2one('bc.planbill', ondelete='cascade')
    contract_id = fields.Many2one('bc.contract', related='planbill_id.contract_id', store=True)
    bussines_id = fields.Many2one('bc.bussines', related='planbill_id.bussines_id')
    resource_id = fields.Many2one('bc.resource')
    expenseitem_id = fields.Many2one('bc.expenseitem')
    state = fields.Selection(related='planbill_id.state', store=True)
    startdate = fields.Date()
    enddate = fields.Date()
    decmoney = fields.Float()
    hxdecmoney = fields.Float(compute='_compute_hxderecmoney', store=True)  # 已核销金额 = 所有核销单的金额之和
    sparemoney = fields.Float(compute='_compute_sparemoney', store=True)  # 未核销金额 = decmoney - hxdecmoney

    remark = fields.Char()
    gather_detail_ids = fields.One2many('bc.gather.detail', 'planbill_detail_id')
    contract_period_id = fields.Many2one('bc.contract.period')

    @api.one
    @api.depends('gather_detail_ids.hxdecmoney')
    def _compute_hxderecmoney(self):
        """
        已核销金额,等于所有核销单的金额之和
        :return:
        """
        self.hxdecmoney = sum(gatherdetail.hxdecmoney for gatherdetail in self.gather_detail_ids)

    @api.one
    @api.depends('gather_detail_ids.hxdecmoney')
    def _compute_sparemoney(self):
        """
        未核销金额 = decmoney - hxdecmoney
        :return:
        """
        self.sparemoney = self.decmoney - self.hxdecmoney

    def get_end_data(self, contract_id, end_date):
        """
        获取合同指定日期后的所有账单
        """
        return self.search([('contract_id', '=', contract_id),
                            ('enddate', '>=', end_date),
                            ('state', '<>', 'close')])

    @api.multi
    def get_bussines_list(self, bussines_id):
        """
        获取所有需要缴费的数据
        :param bussines_id:
        :return:list
        """
        return self.search([('bussines_id', '=', bussines_id),  ])
